import { myRequest } from '@/utils/request.js';

const handleSuccess = (response) => {
    if (response && response.code === 1000) {
        return {
            success: true,
            data: response.data,
            message: response.msg || '操作成功',
        };
    }
    return {
        success: false,
        data: response.data || null,
        message: response.msg || '服务器返回未知错误',
    };
};

const handleError = (error) => {
    console.error('API 请求错误:', error);
    return {
        success: false,
        message: error.message || '网络请求失败',
    };
};

const learningProgressService = {
    async recordView(data) {
        try {
            const response = await new Promise((resolve, reject) => {
                myRequest.request({
                    url: 'learning-progress/record-view',
                    method: 'POST',
                    data: data,
                    success: resolve,
                    error: reject,
                });
            });
            return handleSuccess(response);
        } catch (error) {
            return handleError(error);
        }
    },

    async getProgress(studentId, courseId) {
        try {
            const response = await new Promise((resolve, reject) => {
                myRequest.request({
                    url: `learning-progress?studentId=${studentId}&courseId=${courseId}`,
                    method: 'GET',
                    success: resolve,
                    error: reject,
                });
            });
            return handleSuccess(response);
        } catch (error) {
            return handleError(error);
        }
    },


    async getStudentProgressList(studentId) {
        try {
            const response = await new Promise((resolve, reject) => {
                myRequest.request({
                    url: `learning-progress/students/${studentId}`,
                    method: 'GET',
                    success: resolve,
                    error: reject,
                });
            });
            return handleSuccess(response);
        } catch (error) {
            return handleError(error);
        }
    },
};

export default learningProgressService;
